package com.demo.ssm.job;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.Variable;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

import com.demo.ssm.utils.Configuration;
import com.demo.ssm.utils.TxtFileUtils;  
  
/** 
 * @说明 SNMP4J测试 
 * @version 1.0 
 * @since 
 */  
public class SnmpUtil {  
    private Snmp snmp = null;  
    private Address targetAddress = null;  
  
    public void initComm(String ip) throws IOException {  
        // 设置Agent方的IP和端口  
        targetAddress = GenericAddress.parse("udp:"+ip+"/161");  
        TransportMapping transport = new DefaultUdpTransportMapping();  
        snmp = new Snmp(transport);  
        transport.listen();  
    }  
  
    public ResponseEvent sendPDU(PDU pdu) throws IOException {  
        // 设置 目标  
        CommunityTarget target = new CommunityTarget();  
        target.setCommunity(new OctetString("public"));  
        target.setAddress(targetAddress);  
        // 通信不成功时的重试次数 N+1次  
        target.setRetries(2);  
        // 超时时间  
        target.setTimeout(2 * 1000);  
        // SNMP 版本  
        target.setVersion(SnmpConstants.version2c);  
        // 向Agent发送PDU，并返回Response  
        return snmp.send(pdu, target);  
    }  
  
    public List<Variable> getPDU() throws IOException {
        // PDU 对象  
        PDU pdu = new PDU();
        List<String> txtOid = TxtFileUtils.readTxtFile(Configuration.getDir()+"monitor.txt");
        if(txtOid.size()>0){
        	for(String oid : txtOid){
        		pdu.add(new VariableBinding(new OID(oid))); 
        	}
        }
        // 操作类型  
        pdu.setType(PDU.GET);  
        ResponseEvent revent = sendPDU(pdu);  
        if(null != revent){  
            return readResponse(revent);  
        }
		return null;
    }  
  
    @SuppressWarnings("unchecked")  
    public List<Variable> readResponse(ResponseEvent respEvnt) { 
    	List<Variable> vList = null;
        // 解析Response 
        if (respEvnt != null && respEvnt.getResponse() != null) {
        	vList = new ArrayList<Variable>();
        	
            Vector<VariableBinding> recVBs = (Vector<VariableBinding>) respEvnt.getResponse().getVariableBindings();  
            for (int i = 0; i < recVBs.size(); i++) {  
                VariableBinding recVB = recVBs.elementAt(i);  
                vList.add(recVB.getVariable());
            }  
        }
		return vList;  
    }  
}  